package security

import (
	"net/http"
	"strings"

	"apiGateWay/internal/config"

	"github.com/gin-gonic/gin"
)

// SecurityHeaders 安全头中间件
func SecurityHeaders(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 设置安全响应头
		for key, value := range cfg.Security.Headers {
			c.Header(key, value)
		}

		// IP 白名单检查
		if cfg.Security.IPWhitelist.Enabled {
			if !isIPAllowed(c.ClientIP(), cfg.Security.IPWhitelist.IPs) {
				c.JSON(http.StatusForbidden, gin.H{
					"error": "访问被拒绝",
				})
				c.Abort()
				return
			}
		}

		c.Next()
	}
}

// isIPAllowed 检查 IP 是否在白名单中
func isIPAllowed(ip string, whitelist []string) bool {
	if len(whitelist) == 0 {
		return true
	}

	for _, allowedIP := range whitelist {
		if ip == allowedIP {
			return true
		}
		// 支持 CIDR 格式
		if strings.Contains(allowedIP, "/") {
			// TODO: 实现 CIDR 匹配
			if ip == strings.Split(allowedIP, "/")[0] {
				return true
			}
		}
	}

	return false
}


